package com.tc.banana.framework;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.tc.banana.framework.annotation.Action;
import com.tc.banana.framework.annotation.Controller;
import com.tc.banana.framework.servlet.model.ServletHandle;
import com.tc.banana.framework.util.StringUtil;

/** 
 * @author  wdd 
 * @date 创建时间：2016年4月3日 下午9:12:35 
 */
public class ServletHelper {
	
	private static final Map<String[], ServletHandle> HANDLE_MAP = new HashMap<String[], ServletHandle>();
	
	static {
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		for (Entry<Class<?>, Object> entry : beanMap.entrySet()) {
			Class<?> cls = entry.getKey();
			Object value = entry.getValue();
			if (cls.isAnnotationPresent(Controller.class)) {
				for (Method method : cls.getMethods()){
					if (method.isAnnotationPresent(Action.class)) {
						Action action = method.getAnnotation(Action.class);
						String [] requestUri = StringUtil.toUri(action.value());
						ServletHandle handle = new ServletHandle(requestUri, action.method(), method, value);
						HANDLE_MAP.put(requestUri, handle);
					}
				}
			}
		}
	}

	public static Map<String[], ServletHandle> getHandleMap() {
		return HANDLE_MAP;
	}
	
	public static boolean isMatched(String uri){
		for (Entry<String[], ServletHandle> entry : HANDLE_MAP.entrySet()) {
			String [] uris = entry.getKey();
			if (StringUtil.isContainValue(uri, uris)) {
				return true;
			}
		}
		return false;
	}
	
	public static ServletHandle getMatchedHandler(String uri) {
		for (Entry<String[], ServletHandle> entry : HANDLE_MAP.entrySet()) {
			String [] uris = entry.getKey();
			if (StringUtil.isContainValue(uri, uris)) {
				return HANDLE_MAP.get(uris);
			}
		}
		return null;
	}
	
}
